package de.dlrg.wms.gui.forms;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import de.dlrg.wms.controller.controllers.DisciplineController;
import de.dlrg.wms.gui.forms.generic.GenericForm;
import de.dlrg.wms.model.Discipline;

public class DisciplineForm extends GenericForm {
	private Shell shell;
	private Text nameOfDiscipline;
	private Text description;

	private Discipline disciplineToWork;
	private DisciplineController disciplineController;

	public void open() {
		System.out.println("started main window");
		Display display = Display.getDefault();

		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		System.out.println("stopped mainwindow");
	}

	public void resetForm() {
		this.nameOfDiscipline.setText("");
		this.description.setText("");
	}

	public DisciplineForm(Composite parent, int style,
			final DisciplineController disciplineController, Shell shell) {
		this(parent, style, disciplineController, shell, new Discipline());
	}

	/**
	 * @wbp.parser.constructor
	 */
	public DisciplineForm(Composite parent, int style,
			final DisciplineController disciplineController, Shell shell,
			Discipline disciplineToEdit) {
		super(parent, style);
		this.disciplineToWork = disciplineToEdit;
		this.disciplineController = disciplineController;
		this.shell = shell;

		this.center.setLayout(new GridLayout(2, false));

		Label lblName = new Label(this.center, SWT.NONE);
		lblName.setText("Name");

		nameOfDiscipline = new Text(this.center, SWT.BORDER);
		nameOfDiscipline.setText("nameOfDiscipline");
		nameOfDiscipline.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));

		Label label = new Label(this.center, SWT.NONE);
		label.setText("Description");
		new Label(this.center, SWT.NONE);

		description = new Text(this.center, SWT.BORDER | SWT.MULTI | SWT.WRAP
				| SWT.V_SCROLL);
		description.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true,
				2, 1));
		this.initData();
	}

	@Override
	protected void okClicked() {
		try {

			disciplineToWork.setDescription(description.getText());
			disciplineToWork.setName(nameOfDiscipline.getText());
			disciplineController.validate(disciplineToWork);
			disciplineController.createOrUpdate(disciplineToWork);
			setVisible(false);
			close();
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}

	@Override
	protected void initData() {
		this.nameOfDiscipline.setText(this.disciplineToWork.getName());
		this.description.setText(this.disciplineToWork.getDescription());
	}

}
